# -*- coding:utf8 -*-
"""
Author: gallopingvijay
Email: 1937832819@qq.com
Website: https://www.choudalao.com
Document:https://ai.baidu.com/ai-doc/OCR/1k3h7y3db
ApplyFor:https://console.bce.baidu.com/ai/?_=1619449427519&fromai=1#/ai/ocr/app/list
"""
from aip import AipOcr
import os
import yaml
""" 你的 APPID AK SK """
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''

# pip install baidu-aip


class BaiduBce():
    def __init__(self):
        self.options = {}
        self.setOptions()
        # 配置
        self.configs = self.get_config()
        APP_ID = self.configs['baidu_bce']['APP_ID']
        API_KEY = self.configs['baidu_bce']['API_KEY']
        SECRET_KEY = self.configs['baidu_bce']['SECRET_KEY']
        self.client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

    def dealImg(self, image, type=1, is_local=False):
        '''
        识别
        :param image:图片地址或者url
        :param type:识别接口类型
        :param is_local:是否为本地，False：远程，True,本地
        :return:
        '''
        if type == 1:  # 通用文字识别
            if is_local is False:
                res = self.client.basicGeneralUrl(image)
            else:
                res = self.client.basicGeneral(self.get_file_content(image),
                                               self.options)
        elif type == 2:  # 通用文字识别（高精度版）
            if is_local is True:
                res = self.client.basicAccurate(self.get_file_content(image))
        elif type == 3:  # 网络图片文字识别
            if is_local is False:
                res = self.client.webImageUrl(image)
            else:
                res = self.client.webImage(self.get_file_content(image))
        else:
            if is_local is False:
                res = self.client.basicGeneralUrl(image)
            else:
                res = self.client.basicGeneral(self.get_file_content(image),
                                               self.options)
        return res['words_result'][0]['words']

    def get_file_content(self, filePath):
        '''
        读取图片
        '''
        with open(filePath, 'rb') as fp:
            return fp.read()

    def setOptions(self,
                   language_type='CHN_ENG',
                   detect_direction='false',
                   detect_language='false',
                   probability='false'):
        '''
        如果有可选参数
        :param language_type:
        :param detect_direction:
        :param detect_language:
        :param probability:
        :return:
        '''
        options = {}
        options["language_type"] = language_type
        options["detect_direction"] = detect_direction
        options["detect_language"] = detect_language
        options["probability"] = probability
        self.options = options

    def get_config(self):
        '''
        获取config.yaml配置
        :return:configs
        '''
        # 获取当前文件的上级Realpath
        fileNamePath = os.path.abspath(
            os.path.dirname(os.path.dirname(__file__)))
        # 读取文件
        yamlPath = os.path.join(fileNamePath, 'config.yaml')
        # 加上 ,encoding='utf-8'，处理配置文件中含中文出现乱码的情况。
        file = open(yamlPath, 'r', encoding='utf-8')
        # 读取文件
        cont = file.read()
        # 返回配置
        return yaml.safe_load(cont)
